const app = getApp()
const {
  envList
} = require('../../../envList.js')
var util = require('../../../utils/util.js');
Page({
  data: {
    envList,
    selectedEnv: envList[0],
    TabCur: 0,
    scrollLeft: 0,
    tabList: ['卡券仓库', '签发卡券'],
    lssue_list: [],
    lssue_length: 0,
    limit: 5,
    skip: 0,
    numList: [{
      name: '定义信息',
      bindtap: 'scanCode'
    }, {
      name: '导出数据',
      bindtap: 'scanCode'
    }, {
      name: '完成签发',
      bindtap: ''
    }],
    num: 0,
    card_id_num: 10,
    card_pwd_num: 16,
    goods_number: 1,
    cardCur: 0,
    swiperList: [{
      id: 1,
      type: 'image',
      url: 'https://i0.hdslb.com/bfs/album/9518434ea2d97ea24be507b9fb786e67876dadd1.png'
    }, {
      id: 2,
      type: 'image',
      url: 'https://i0.hdslb.com/bfs/album/7f5bb80be870bcfe4e2f2d0d1699efa76052bf08.png'
    }, ],
    custom: false,
    imgList: [],
    cardCur: 0
  },
  onLoad: function (options) {
    this.tabGetlssueCards();
    this.getCardImage();
  },
  // 获取卡面
  getCardImage() {
    wx.cloud.callFunction({
      name: "main",
      data: {
        type: 'getCardImage'
      },
      success: res => {
        // console.log(res);
        this.setData({
          cardList: res.result.data,
          card_url: res.result.data[0].image_url,
          expiration_date: this.getNowDate()
        });
      }
    })
  },
  // 卡片切换
  cardSwiper(e) {
    this.setData({
      cardCur: e.detail.current,
      card_url: this.data.cardList[e.detail.current].image_url
    })
  },
  tabSelect(e) {
    this.setData({
      TabCur: e.currentTarget.dataset.id,
      scrollLeft: (e.currentTarget.dataset.id - 1) * 60
    });
    if (e.currentTarget.dataset.id == 1) {
      if (util.get('goods_list', 'outTime') == 'outTime') {
        this.getGoodsList();
      } else {
        console.log('【签发卡券】页面数据调用goods_list缓存。');
        wx.hideLoading();
        if (wx.getStorageSync('goods_list') != '') {
          this.setData({
            goods_list: wx.getStorageSync('goods_list')
          })
        } else {
          wx.showModal({
            title: '暂无商品',
            content: '发布商品后再选择商品签发卡券',
            confirmColor: app.globalData.system_color,
            showCancel: false,
            success: res => {
              if (res.confirm) {
                wx.redirectTo({
                  url: '../goods/goods',
                })
              }
            }
          })
        }
      }
    } else {
      this.tabGetlssueCards();
    }
  },
  // 获取卡券列表
  tabGetlssueCards() {
    if (util.get('lssue_list', 'outTime') == 'outTime') {
      this.setData({
        limit: 5,
        skip: 0,
        lssue_list: []
      });
      this.getlssueCards(this.data.limit, this.data.skip);
    } else {
      console.log('【卡券仓库】页面数据调用缓存。');
      wx.hideLoading();
      this.setData({
        lssue_list: wx.getStorageSync('lssue_list'),
        lssue_length: wx.getStorageSync('lssue_length')
      })
    }
  },
  // 获取签发记录
  getlssueCards(limit, skip) {
    // console.log('limit:' + limit + ';skip:' + skip);
    var that = this;
    let times = 120;
    wx.showLoading({
      title: '系统正在处理',
    })
    wx.cloud.callFunction({
      name: "getlssueCards",
      data: {
        limit: limit,
        skip: skip
      },
      success: res => {
        wx.hideLoading();
        // console.log(res);
        if (res.result == 0) {
          that.setData({
            lssue_list: []
          });
        } else {
          that.setData({
            limit: limit,
            lssue_length: res.result.lssue_length,
            lssue_list: that.data.lssue_list.concat(res.result.lssue_list)
          });
          // 缓存times秒
          if (that.data.lssue_length == that.data.lssue_list.length) {
            util.put('lssue_list', that.data.lssue_list, times);
            util.put('lssue_length', that.data.lssue_length, times);
          }
        }
      }
    })
  },
  // 复制信息到粘贴板
  copyData(e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.info,
      success() {
        wx.showToast({
          title: '复制成功',
          icon: 'success',
          duration: 2000
        })
      }
    })
  },
  // 上拉触底，获取签发记录
  onReachBottom() {
    if (this.data.TabCur == 0) {
      console.log('上拉触底');
      if (this.data.lssue_list.length < this.data.lssue_length) {
        this.getlssueCards(this.data.limit + 5, this.data.skip + this.data.limit);
      } else {
        wx.showToast({
          title: '数据加载完毕',
          icon: 'success',
        })
      }
    }
  },
  // 获取发布的商品列表
  getGoodsList() {
    var that = this;
    let times = 120;
    wx.showLoading({
      title: '系统正在处理',
    })
    wx.cloud.callFunction({
      name: "getGoodsList",
      data: {
        limit: 100,
        skip: 0
      },
      success: res => {
        wx.hideLoading();
        // console.log(res);
        if (res.result.goods_length == 0) {
          that.setData({
            goods_list: []
          });
          wx.showModal({
            title: '暂无商品',
            content: '发布商品后再选择商品签发卡券',
            confirmColor: app.globalData.system_color,
            showCancel: false,
            success: res => {
              if (res.confirm) {
                wx.redirectTo({
                  url: '../goods/goods',
                })
              }
            }
          })
        } else {
          that.setData({
            goods_list: res.result.goods_list
          });
          // 缓存times秒
          util.put('goods_list', that.data.goods_list, times);
        }
      }
    })
  },
  // 商品数量
  getGoodsNum(e) {
    if (e.detail.value > 100) {
      wx.showToast({
        title: '最多100件',
        icon: 'error',
        duration: 2000
      });
      this.setData({
        goods_number: 1
      })
    } else {
      this.setData({
        goods_number: e.detail.value
      })
    }
  },
  // 卡号位数
  getCardIdNum(e) {
    if (e.detail.value > 10 || e.detail.value < 5) {
      wx.showToast({
        title: '卡号5至10位',
        icon: 'error',
        duration: 2000
      });
      this.setData({
        card_id_num: null
      })
    } else {
      this.setData({
        card_id_num: e.detail.value
      })
    }
  },
  // 密码位数
  getCardPwdNum(e) {
    if (e.detail.value > 16 || e.detail.value < 5) {
      wx.showToast({
        title: '密码5至16位',
        icon: 'error',
        duration: 2000
      });
      this.setData({
        card_pwd_num: null
      })
    } else {
      this.setData({
        card_pwd_num: e.detail.value
      })
    }
  },
  // 签发数量
  getCardNum(e) {
    if (e.detail.value > 50) {
      wx.showToast({
        title: '最多50张',
        icon: 'error',
        duration: 2000
      });
      this.setData({
        card_num: null
      })
    } else {
      this.setData({
        card_num: e.detail.value
      })
    }
  },
  // 提交信息
  submitInfo() {
    if (this.data.card_id_num != null && this.data.card_pwd_num != null && this.data.card_num != null && this.data.card_num != '' && this.data.goods_id != null) {
      this.getRandomStr();
    } else {
      wx.showToast({
        title: '参数未填写',
        icon: 'error'
      })
    }
  },
  // 可提商品
  goodsPicker(e) {
    this.setData({
      index: e.detail.value,
      goods_id: this.data.goods_list[e.detail.value]._id
    })
  },
  // 生成卡密
  getRandomStr() {
    this.setData({
      btn_disabled: 'disabled'
    });
    wx.showLoading({
      title: '正在签发...',
    });
    if (this.data.custom == true) {
      wx.cloud.uploadFile({
        cloudPath: "card_image/" + wx.getStorageSync('openid') + Date.now() + ".png",
        filePath: this.data.imagePath, // 文件路径
        success: res => {
          // 上传数据
          this.uploadData(res.fileID);
        },
        fail: err => {
          wx.showModal({
            title: '签发失败',
            content: '图片上传失败',
            showCancel: false,
            success: res => {
              this.setData({
                btn_disabled: ''
              });
            }
          })
        }
      })
    } else {
      this.uploadData();
    }
  },
  uploadData(fileID) {
    wx.cloud.callFunction({
      name: "addCards",
      data: {
        card_num: this.data.card_num,
        card_id_num: this.data.card_id_num,
        card_pwd_num: this.data.card_pwd_num,
        goods_id: this.data.goods_id,
        goods_number: this.data.goods_number,
        fileID: fileID,
        custom: this.data.custom,
        expiration_date: this.data.expiration_date,
        card_url: this.data.card_url
      },
      success: res => {
        wx.hideLoading();
        // console.log(res);
        wx.showModal({
          title: '签发成功',
          content: '前往卡券仓库查看卡券信息',
          showCancel: false,
          confirmColor: app.globalData.system_color,
          success: res => {
            wx.removeStorageSync('lssue_length');
            wx.removeStorageSync('lssue_list');
            this.setData({
              TabCur: 0,
              btn_disabled: ''
            });
            this.tabGetlssueCards();
          }
        })
      },
      fail: res => {
        wx.hideLoading();
        console.log('签发失败');
        console.log(res);
        wx.showModal({
          title: '签发失败',
          content: '请尝试减少签发数量',
          showCancel: false,
          success: res => {
            this.setData({
              btn_disabled: ''
            });
          }
        })
      }
    })
  },
  // 卡券仓库预览图片
  downloadImage(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.url, // 当前显示图片的http链接
      urls: [e.currentTarget.dataset.url] // 需要预览的图片http链接列表
    })
  },
  // 出售卡券
  sellCard(e) {
    this.setData({
      sell_card: true,
      card_number: e.currentTarget.dataset.cid,
      card_password: e.currentTarget.dataset.cpwd,
      goods_name: e.currentTarget.dataset.cgn,
      goods_type: e.currentTarget.dataset.cgt,
      card_id: e.currentTarget.dataset.id,
      card_url: e.currentTarget.dataset.curl,
      expiration_date: e.currentTarget.dataset.expd
    })
  },
  // 分享提货卡
  onShareAppMessage: function (e) {
    if (e.from === 'button') {
      // 来自页面内转发按钮
      return {
        title: '点击领取您的提货卡',
        path: 'pages/customer/card/card?card_number=' + this.data.card_number + '&card_password=' + this.data.card_password + '&goods_name=' + this.data.goods_name + '&goods_type=' + this.data.goods_type + '&card_url=' + this.data.card_url + '&expiration_date=' + this.data.expiration_date,
        imageUrl: 'https://i0.hdslb.com/bfs/album/3793af5ad62569b7b6e7b5ad2bfa0687cb56e477.jpg',
      }
    }
  },
  // 更新卡券信息
  updateCard() {
    // 更新卡券信息status=2,待提货
    wx.showLoading({
      title: '系统正在处理',
    });
    this.setData({
      sell_card: false
    });
    wx.cloud.callFunction({
      name: "updateCards",
      data: {
        card_id: this.data.card_id,
        status: 2
      },
      success: res => {
        wx.hideLoading();
        // console.log('this.data.card_id:' + this.data.card_id);
        // console.log(res);
        if (res.result.stats.updated == 1) {
          console.log('卡券更新状态2成功');
          wx.removeStorageSync('lssue_list');
          wx.removeStorageSync('lssue_length');
          this.tabGetlssueCards();
        }
      },
      fail: res => {
        wx.hideLoading();
        wx.showToast({
          title: '更新状态失败',
          icon: 'error'
        }, 2000);
        console.log('卡券更新状态2失败');
      }
    })
  },
  // 自定义图片
  changeCustom(e) {
    this.setData({
      custom: !e.currentTarget.dataset.custom
    })
  },
  // 选择图片
  ChooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], //从相册选择
      success: (res) => {
        if (this.data.imgList.length != 0) {
          this.setData({
            imgList: this.data.imgList.concat(res.tempFilePaths),
          })
        } else {
          let path = res.tempFilePaths[0];
          // console.log('path:' + path);
          this.setData({
            imgList: res.tempFilePaths,
            // 文件转码为base64
            // fileContent: wx.getFileSystemManager().readFileSync(path, 'base64'),
            imagePath: res.tempFilePaths[0]
          })
        }
      }
    });
  },
  // 预览图片
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  // 删除图片
  DelImg(e) {
    wx.showModal({
      title: '删除图片',
      content: '确定要删除该图片吗？',
      confirmColor: '#10c55b',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },
  // 改变日期
  DateChange(e) {
    this.setData({
      expiration_date: e.detail.value
    })
  },
  //获取当前日期
  getNowDate(e) {
    var date = new Date();
    var todate = date.getFullYear() + "-" + ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : date.getMonth() + 1) + "-" + (date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate());
    return todate;
  },
  // 隐藏卡券二维码
  hideModal(e) {
    this.setData({
      sell_card: false,
      modalName: null
    })
  },
  // 展示卡券二维码
  showQrcode(e) {
    this.setData({
      modalName: 'codeModal',
      goods_name: e.currentTarget.dataset.name,
      code_url: e.currentTarget.dataset.curl,
      goods_type: e.currentTarget.dataset.type,
      goods_cnumber: e.currentTarget.dataset.cnumber,
    })
  }
})